package cn.fboost.mtos.interceptor;

import cn.fboost.mtos.annotation.RoleIs;
import cn.fboost.mtos.dto.Response;
import cn.fboost.mtos.dto.internal.Session;
import cn.fboost.mtos.util.InterceptorResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;

@Slf4j
@Component
public class RoleInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object handler) {
        if (!(handler instanceof HandlerMethod))
            return true;

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        Session session = (Session) request.getAttribute("current_session");
        Class<?> clazz = handlerMethod.getBean().getClass();

        boolean inMethod = method.isAnnotationPresent(RoleIs.class);
        boolean inClass = clazz.isAnnotationPresent(RoleIs.class);
        if (inMethod || inClass) {
            RoleIs annotation;
            if (inMethod) {
                annotation = method.getAnnotation(RoleIs.class);
            } else {
                annotation = clazz.getAnnotation(RoleIs.class);
            }

            if (Arrays.binarySearch(annotation.value(), session.getRole()) < 0) {
                Response resp = Response.builder().failure().msg("无权访问").build();
                InterceptorResponseUtil.response(response, resp);
                return false;
            }
        }

        return true;
    }
}
